package com.fancy.learncenter.ui.activity;

import android.Manifest;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.util.Util;
import com.czt.mp3recorder.MP3Recorder;
import com.facebook.drawee.view.SimpleDraweeView;
import com.fancy.learncenter.R;
import com.fancy.learncenter.bean.AudioBean;
import com.fancy.learncenter.common.Constant;
import com.fancy.learncenter.common.Player;
import com.fancy.learncenter.db.RecorderAudioDBManager;
import com.fancy.learncenter.ui.activity.base.BaseActivity;
import com.fancy.learncenter.utils.DataUtil;
import com.fancy.learncenter.utils.FileUtils;
import com.fancy.learncenter.utils.LogUtil;
import com.fancy.learncenter.utils.PermissionCustomManager;
import com.fancy.learncenter.utils.PermissionHelper;
import com.fancy.learncenter.utils.ProgressUtil;
import com.fancy.learncenter.utils.ToastUtil;
import com.fancy.learncenter.utils.Utils;
import com.shuyu.waveview.AudioPlayer;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 录音
 */
public class RecorderActivity extends BaseActivity {
    MP3Recorder mRecorder;

    public static String FILEPATH_KEY = "PathKey";
    public static String AUDIO_NAME_KEY = "Name_Key";


    boolean mIsRecord = false;

    AnimationDrawable animLeft;
    AnimationDrawable animRight;
    AudioPlayer audioPlayer;

    String filePath;
    @Bind(R.id.recordPause)
    Button recordPause;
    @Bind(R.id.stop)
    Button stop;
    @Bind(R.id.reset)
    Button reset;
    @Bind(R.id.btn_layout)
    LinearLayout btnLayout;
    @Bind(R.id.cancer)
    ImageView cancer;
    @Bind(R.id.record)
    ImageView record;
    @Bind(R.id.submit)
    ImageView submit;
    @Bind(R.id.record_status)
    TextView recordStatus;
    @Bind(R.id.record_animation_left)
    ImageView recordAnimationLeft;
    @Bind(R.id.record_animation_right)
    ImageView recordAnimationRight;
    @Bind(R.id.play_img)
    ImageView playImg;
    @Bind(R.id.recordTime)
    TextView recordTime;
    @Bind(R.id.sb_audio)
    ProgressBar sbAudio;
    @Bind(R.id.play_bg)
    SimpleDraweeView playBg;
    @Bind(R.id.play_introduce)
    TextView playIntroduce;
    @Bind(R.id.record_status_left)
    TextView recordStatusLeft;
    @Bind(R.id.back_image)
     ImageView backImage;
    @Bind(R.id.right_img)
     ImageView rightImg;
    @Bind(R.id.title)
    TextView title;


    //    String musicName = "小小阅读家";
    //封面图
    String showResourceCoverImg = "";
    //资源名称
    String showResourceName = "";

    Player player;

    PermissionHelper mHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recorder, Status.STATUS);
        ButterKnife.bind(this);

        showResourceCoverImg = getIntent().getStringExtra(Constant.showResourceCoverImg);
        showResourceName = getIntent().getStringExtra(Constant.showResourceName);
//        initToolbar(showResourceName);
        title.setText(showResourceName);
        backImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                finish();
            }
        });
        playBg.setImageURI(showResourceCoverImg);
        sbAudio.setMax(600);
        animLeft = (AnimationDrawable) recordAnimationLeft.getBackground();
        animRight = (AnimationDrawable) recordAnimationRight.getBackground();

        audioPlayer = new AudioPlayer(this, new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case AudioPlayer.HANDLER_CUR_TIME://更新的时间
//                        curPosition = (int) msg.obj;
//                        playText.setText(toTime(curPosition) + " / " + toTime(duration));
                        break;
                    case AudioPlayer.HANDLER_COMPLETE://播放结束
//                        playText.setText(" ");
//                        mIsPlay = false;
                        break;
                    case AudioPlayer.HANDLER_PREPARED://播放开始
//                        duration = (int) msg.obj;
//                        playText.setText(toTime(curPosition) + " / " + toTime(duration));
                        break;
                    case AudioPlayer.HANDLER_ERROR://播放错误

                        break;
                }

            }
        });
        ArrayList<String> permissionList = new ArrayList<>();
        if (!mHelper.hasPermissions(RecorderActivity.this, Manifest.permission.RECORD_AUDIO)) {
            permissionList.add(Manifest.permission.RECORD_AUDIO);
        }
        if (!mHelper.hasPermissions(RecorderActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }
        mHelper = new PermissionHelper(this);

        mHelper.requestPermissions("请授予非凡学习文件获取权限！",
                new PermissionHelper.PermissionListener() {
                    @Override
                    public void doAfterGrand(String... permission) {
                        LogUtil.MyLog("mHelper", "========确认=======");
                    }

                    @Override
                    public void doAfterDenied(final String... permission) {
                        LogUtil.MyLog("mHelper", "========拒绝=======" + permission.toString());
                        mHelper.showMessageOKCancel(getResources().getString(R.string.recode_permission), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                ArrayList<String> permissionList = new ArrayList<>();
                                if (!mHelper.hasPermissions(RecorderActivity.this, Manifest.permission.RECORD_AUDIO)) {
                                    permissionList.add(Manifest.permission.RECORD_AUDIO);
                                }
                                if (!mHelper.hasPermissions(RecorderActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                                    permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
                                }
                                mHelper.executePermissionsRequest(RecorderActivity.this, (String[]) permissionList.toArray(new String[permissionList.size()]), mHelper.REQUEST_PERMISSION_CODE);
                            }
                        });
                    }
                }, (String[]) permissionList.toArray(new String[permissionList.size()]));

    }


    /**
     * 开始录音
     */
    private void resolveRecord() {
        filePath = FileUtils.getRecorderAudioPath();
        File file = new File(filePath);
        if (!file.exists()) {
            if (!file.mkdirs()) {
                Toast.makeText(this, "创建文件失败", Toast.LENGTH_SHORT).show();
                return;
            }
        }
        filePath = filePath + DataUtil.getCurTimeByFormat("yyyy-MM-dd hh:mm:ss") + ".mp3";
        mRecorder = new MP3Recorder(new File(filePath));

        AudioManager audioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
        // 关闭麦克风
        audioManager.setMicrophoneMute(true);
        mRecorder.setErrorHandler(new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.what == MP3Recorder.ERROR_TYPE) {
                    Toast.makeText(RecorderActivity.this, "没有麦克风权限", Toast.LENGTH_SHORT).show();
                    resolveError();
                }
            }
        });

        try {
            mRecorder.start();
            startRecorderUi();
        } catch (IOException e) {
            e.printStackTrace();

            LogUtil.MyLog("mRecorder", "======mRecorder=====" + e);
            Toast.makeText(this, "录音出现异常", Toast.LENGTH_SHORT).show();
            resolveError();
            return;
        }
        mIsRecord = true;
    }

    private void startRecorderUi() {
        startTime();
        recordStatus.setText("停止录音");
        recordStatusLeft.setText("正在录制");
        record.setImageResource(R.mipmap.speaking);
        animLeft.start();
        animRight.start();
        recordAnimationLeft.setVisibility(View.VISIBLE);
        recordAnimationRight.setVisibility(View.VISIBLE);
        cancer.setVisibility(View.GONE);
        submit.setVisibility(View.GONE);
        playIntroduce.setVisibility(View.GONE);
        playImg.setVisibility(View.GONE);
    }

    private void pauseRecorderUi() {

        if (timer != null) {
            timer.cancel();
        }

        recordStatus.setText("继续录音");
        recordStatusLeft.setText("准备录制");
        record.setImageResource(R.mipmap.speak);
        animLeft.stop();
        animRight.stop();
        recordAnimationLeft.setVisibility(View.GONE);
        recordAnimationRight.setVisibility(View.GONE);
        cancer.setVisibility(View.VISIBLE);
        submit.setVisibility(View.VISIBLE);
        playIntroduce.setVisibility(View.VISIBLE);
        playImg.setVisibility(View.VISIBLE);
    }

    private void stopRecorderUi() {
        timeValue = 0;
        recordStatus.setText("开始录音");
        recordStatusLeft.setText("准备录制");
        record.setImageResource(R.mipmap.speak);
        animLeft.stop();
        animRight.stop();
        recordAnimationLeft.setVisibility(View.GONE);
        recordAnimationRight.setVisibility(View.GONE);
        cancer.setVisibility(View.GONE);
        submit.setVisibility(View.GONE);
        playIntroduce.setVisibility(View.GONE);
        playImg.setVisibility(View.GONE);
    }


    /**
     * 录音异常
     */
    private void resolveError() {
        FileUtils.deleteFile(filePath);
        filePath = "";
        if (mRecorder != null && mRecorder.isRecording()) {
            mRecorder.stop();
        }
    }

    @Override
    public void onPause() {
        super.onPause();

        if (mRecorder != null) {
            mRecorder.setPause(true);
            pauseRecorderUi();
        }
    }


    private void changeRecordUi() {
        if (mRecorder != null) {
            if (mRecorder.isPause()) {
                mRecorder.setPause(false);
                startRecorderUi();
                LogUtil.MyLog("mRecorder", "=======暂定=====");
            } else {
                mRecorder.setPause(true);
                pauseRecorderUi();
                LogUtil.MyLog("mRecorder", "=======继续播放=====");
            }
        } else {
            resolveRecord();

        }
    }

    private boolean isDeleteAudio = true;
    PermissionCustomManager manager;

    @OnClick({R.id.record, R.id.stop, R.id.cancer, R.id.recordPause, R.id.submit, R.id.play_img})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.record:
//                manager = new PermissionCustomManager(this, Manifest.permission.RECORD_AUDIO, new PermissionCustomManager.OnPermissionListener() {
//                    @Override
//                    public void onAccept() {
//
//                    }
//                });

                changeRecordUi();
                break;
            case R.id.submit:
                mRecorder.stop();
                mRecorder = null;
                stopRecorderUi();
                isDeleteAudio = false;

                Intent intent = new Intent(this, RelaseAudioActivity.class);
                intent.putExtra(FILEPATH_KEY, filePath);
                intent.putExtra(AUDIO_NAME_KEY, showResourceName);
                intent.putExtra(Constant.showResourceCoverImg, showResourceCoverImg);
                startActivity(intent);
                this.finish();
                break;
            case R.id.cancer:
                mRecorder.stop();
                mRecorder = null;
                FileUtils.deleteFile(filePath);
                stopRecorderUi();
                timer.cancel();
                recordTime.setText("00:00/10:00");
                sbAudio.setProgress(0);
                break;
            case R.id.play_img:
                playRecord();
                break;
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
    }


    @Override
    public void finish() {
        super.finish();
        if (isDeleteAudio) {
            if (!TextUtils.isEmpty(filePath)) {
                FileUtils.deleteFile(filePath);
            }
        } else {
            updataMusic(filePath);
        }
    }


    /**
     * 播放
     */
    private void playRecord() {
        if (TextUtils.isEmpty(filePath) || !new File(filePath).exists()) {
            ToastUtil.show("文件不存在");
            return;
        }
        audioPlayer.playUrl(filePath);

    }

    Timer timer;
    long timeValue = 0;

    private void startTime() {
        timer = new Timer();

        timer.schedule(new TimerTask() {
            @Override
            public void run() {

                runOnUiThread(new Runnable() {  // UI thread
                    @Override
                    public void run() {
                        timeValue++;
                        long time = (timeValue) / 2;
                        sbAudio.setProgress((int) time);
                        recordTime.setText(DataUtil.formatPlayTime(time * 1000) + "  /  10:00");
                        //超过10分钟。停止录音
                        if(time >= 600){

                            ToastUtil.show("最多只能录制10分钟");
                            changeRecordUi();
                        }

                    }
                });

            }
        }, 500, 500);
    }

    private void updataMusic(String path) {
        //更新媒体库
        Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        scanIntent.setData(Uri.fromFile(new File(path)));
        sendBroadcast(scanIntent);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        mHelper.handleRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}
